package com.zdkj.subway.st.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.exceltools.ExcelUtil;
import com.zdkj.common.core.exceltools.IExcelExport;
import com.zdkj.common.core.exceltools.IExcelParser;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.entity.SwStTicketReceive;
import com.zdkj.subway.st.service.impl.SwStTicketReceiveServiceImpl;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @ProjectName: zdkj
 * @Package: com.zdkj.subway.st.controller
 * @ClassName: SwStTicketReceiveController
 * @Description:
 * @Author: kangjian
 * @CreateDate: 2020/1/8 14:48
 * @Version: 1.0
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swStTicketReceive")
@Api(value = "swStTicketReceive", tags = "车票领用管理")
public class SwStTicketReceiveController {

    private final SwStTicketReceiveServiceImpl swStTicketReceiveService;

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(swStTicketReceiveService.getById(id));
    }

    @GetMapping("/page")
    public R<IPage> getDictPage(Page page, SwStTicketReceive swStTicketReceive) {
        //出库时间
        List<String> dateCondition = swStTicketReceive.getDates1();
        QueryWrapper<SwStTicketReceive> lambdaQueryWrapper = Wrappers.query(swStTicketReceive);

        if (ObjectUtil.isNotEmpty(dateCondition)) {
            lambdaQueryWrapper.lambda().between(SwStTicketReceive::getOutStorageTime, dateCondition.get(0), dateCondition.get(1));
        }
        //LambdaQueryWrapper<SwStTicketReceive> lambdaQueryWrapper = Wrappers.lambdaQuery(swStTicketReceive);
        lambdaQueryWrapper.orderByDesc("out_storage_time");
        String reTimeDTO = swStTicketReceive.getReceiveTimeDTO();
        //String outTimeDTO = swStTicketReceive.getOutStorageTimeDTO();
        if (StringUtils.isNotBlank(reTimeDTO)) {
            lambdaQueryWrapper.lambda().likeRight(SwStTicketReceive::getReceiveTime, reTimeDTO);
        }
        /*if (StringUtils.isNotBlank(outTimeDTO)) {
            lambdaQueryWrapper.lambda().likeRight(SwStTicketReceive::getOutStorageTime, outTimeDTO);
        }*/
        return R.ok(swStTicketReceiveService.page(page, lambdaQueryWrapper));
    }

    @SysLog("车票领用保存信息")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_ticket_receive_add')")
    public R save(@Valid @RequestBody SwStTicketReceive swStTicketReceive) {
        PigxUser user = SecurityUtils.getUser();
        swStTicketReceive.setCreatorName(user.getUsername());
        swStTicketReceive.setCreatorId(user.getId());
        return R.ok(swStTicketReceiveService.save(swStTicketReceive));
    }

    @SysLog("删除车票领用信息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_ticket_receive_delete')")
    public R removeById(@PathVariable String id) {
        return R.ok(swStTicketReceiveService.removeById(id));
    }

    @PutMapping
    @SysLog("修改车票领用信息")
    @PreAuthorize("@pms.hasPermission('st_ticket_receive_update')")
    public R updateById(@Valid @RequestBody SwStTicketReceive swStTicketReceive) {
        PigxUser user = SecurityUtils.getUser();
        swStTicketReceive.setCreatorName(user.getUsername());
        swStTicketReceive.setCreatorId(user.getId());
        return R.ok(swStTicketReceiveService.updateById(swStTicketReceive));
    }

    @PutMapping("/receiveticket")
    @SysLog("已领用车票")
    public R receiveticket(@Valid @RequestBody SwStTicketReceive receive) {
        SwStTicketReceive swStTicketReceive = swStTicketReceiveService.getById(receive.getId());
        PigxUser user = SecurityUtils.getUser();
        swStTicketReceive.setCreatorName(user.getUsername());
        swStTicketReceive.setCreatorId(user.getId());
        swStTicketReceive.setIsReceive("是");
        swStTicketReceive.setReceiveTime(LocalDateTime.now());
        return R.ok(swStTicketReceiveService.updateById(swStTicketReceive));
    }

    @PostMapping(value = "/import")
    @SysLog("导入车票领用信息")
    @PreAuthorize("@pms.hasPermission('st_ticket_receive_import')")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        try {
            File efile = MultipartFileToFile.multipartFileToFile(file);
            Workbook workbook = ExcelUtil.chooseWorkbook(efile);
            Sheet sheet = workbook.getSheetAt(0);
            IExcelParser excelParser = SpringContextHolder.getBean("commonExcelParse");
            List<SwStTicketReceive> list = excelParser.parse(sheet, SwStTicketReceive.class);
            swStTicketReceiveService.saveBatch(list);
            return R.ok("1", "导入成功");
        } catch (Exception e) {
            log.error("", e);
            return R.failed("Excel导入失败！");
        }
    }

    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('st_ticket_receive_export')")
    public void exportExcel(SwStTicketReceive swStTicketReceive, HttpServletResponse response) {
        List<SwStTicketReceive> swStTicketReceivelist = swStTicketReceiveService.list(Wrappers.query(swStTicketReceive));
        IExcelExport excelExport = SpringContextHolder.getBean("commonExcelExport");//设置头信息
        Workbook workbook = excelExport.parse(swStTicketReceivelist);
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
